// 导入白名单
import config from "./config.js";

export default function initApp() {
  let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
  list.forEach((item) => {
    // 通过遍历将4种路由跳转方式分别添加拦截器
    uni.addInterceptor(item, {
      // invoke 	拦截前触发
      invoke(e) {
        // 获取token
        const token = uni.getStorageSync("token") || "";
        // 获取要跳转的页面路径
        let url = e.url.split("?")[0];
        // 查找要访问的页面在不在白名单内
        let notNeed = config.whiteList.includes(url);
        if (token) {
          if (url === config.loginPage) {
            uni.showToast({
              title: "已经登录",
              icon: "none",
            });
            return false;
          } else {
            return e;
          }
        } else {
          if (notNeed) {
            return e;
          } else {
            uni.showModal({
              title: "友情提示",
              content: "请先登录",
              success(res) {
                if (res.confirm) {
                  uni.navigateTo({
                    url: config.loginPage,
                  });
                } else {
                  uni.navigateBack();
                }
              },
            });
            return false;
          }
        }
      },
      // 失败回调拦截
      fail(err) {
        uni.showModal({
          content: err,
          showCancel: false,
        });
      },
    });
  });
}
